<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <Input v-model:value="record[column.key]" />
        </template>
        <template v-if="column.key === 'title'">
          <Input v-model:value="record[column.key]" />
        </template>
        <template v-if="column.key === 'filename'">
          <Upload
            :maxCount="1"
            :before-upload="(file) => handleBeforeUploadFilename(file, { record, key: column.key })"
            accept=".docx"
          >
            <a-button>
              <upload-outlined />
              上传
            </a-button>
          </Upload>
        </template>
        <template v-if="column.key === 'filenameTail'">
          <Upload
            :maxCount="1"
            :before-upload="(file) => handleBeforeUploadFilename(file, { record, key: column.key })"
            accept=".docx"
          >
            <a-button>
              <upload-outlined />
              上传
            </a-button>
          </Upload>
        </template>
        <template v-if="column.key === 'typeCodes'">
          <TreeSelect
            v-model:value="record[column.key]"
            style="width: 100%"
            :tree-data="flowTree"
            :field-names="{ label: 'name', value: 'code' }"
            :show-search="true"
            :multiple="true"
            treeNodeFilterProp="name"
            @change="(val, names) => getFlowInfo(val, names, record)"
          />
        </template>
        <template v-if="column.key === 'depts'">
          <TreeSelect
            v-model:value="record[column.key]"
            style="width: 100%"
            :tree-data="departList"
            :field-names="{ label: 'name', value: 'code' }"
            :show-search="true"
            :multiple="true"
            treeNodeFilterProp="name"
            @change="(val, names) => getDepartInfo(val, names, record)"
          />
        </template>
        <template v-if="column.key === 'unitCode'">
          <TreeSelect
            v-model:value="record[column.key]"
            style="width: 100%"
            :tree-data="unitCodeList"
            :field-names="{ label: 'name', value: 'code' }"
            :show-search="true"
            treeNodeFilterProp="name"
          />
        </template>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '修改',
              onClick: handleEdit.bind(null, record),
              ifShow: () => !!record.id,
            },
            {
              icon: 'ant-design:save-outlined',
              tooltip: '保存',
              onClick: handleSave.bind(null, record),
              ifShow: () => !record.id,
            },
            {
              icon: 'ant-design:delete-outlined',
              tooltip: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
              ifShow: () => !!record.id,
            },
            {
              icon: 'ant-design:download-outlined',
              tooltip: '下载头',
              onClick: handleDown.bind(null, record, 1),
              ifShow: () => !!record.id,
            },
            {
              icon: 'ant-design:download-outlined',
              tooltip: '下载尾',
              onClick: handleDown.bind(null, record, 2),
              ifShow: () => !!record.id && record.hasTail,
            },
          ]"
        />
        <div></div>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getFlowGetDirTreeAll } from '/@/api/flowManage/flowManage';
  import {
    getPaperList,
    getPaperCreate,
    getPaperUpdate,
    getPaperDel,
    getFlowGetTemplateFile,
  } from '/@/api/flowManage/flowManage';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { Input, TreeSelect, Upload } from 'ant-design-vue';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import {
    columns,
    searchFormSchema,
    getDepartmentData,
    setParams,
  } from './officialDocumentTemplate.data';
  import { isArray } from '/@/utils/is';
  import { downloadByData } from '/@/utils/file/download';

  export default defineComponent({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'officialDocumentTemplate',
    components: { BasicTable, TableAction, Input, TreeSelect, Upload, UploadOutlined },
    setup() {
      const { createMessage, createConfirm } = useMessage();
      const departList = ref([]);
      const flowTree = ref([]);
      const unitCodeList = ref<Recordable[]>([]);
      const fetch = async () => {
        departList.value = await getDepartmentData();
        flowTree.value = await getFlowGetDirTreeAll();
        unitCodeList.value = [
          {
            code: '-1',
            name: '--公共模板--',
          },
        ];
        unitCodeList.value = [...unitCodeList.value, ...departList.value];
      };
      onMounted(fetch);

      const [registerTable, { reload, setProps, getForm, getDataSource, setTableData }] = useTable({
        title: '公文模板',
        api: getPaperList,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        searchInfo: {
          action: 'search',
        }, //额外的参数
        afterFetch: (data) => {
          console.log('data', data);
          const newData = data;
          if (isArray(newData)) {
            newData.forEach((item) => {
              if (item.depts) {
                item.depts = item.depts.split(',');
              } else {
                item.depts = [];
              }
              if (item.typeCodes) {
                item.typeCodes = item.typeCodes.split(',');
              } else {
                item.typeCodes = [];
              }
            });
            setTableData(newData);
          }
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: false,
        rowKey: 'id',
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      //新增
      const handleCreate = () => {
        console.log('getDataSource', getDataSource());
        let data = getDataSource();
        data.push({ unitCode: '-1' });
      };
      //新增保存
      const handleSave = async (record) => {
        if (!record['title']) {
          return createMessage.warning('名称不能为空');
        }
        if (!record['filename']) {
          return createMessage.warning('文件头不能为空');
        }
        try {
          handleSetProps(true);
          const params = setParams(record);
          let Files = new FormData();
          for (let v in params) {
            Files.append(v, params[v]);
          }
          await getPaperCreate(Files);
          createMessage.success('操作成功');
          handleSuccess();
        } finally {
          handleSetProps(false);
        }
      };

      //获取部门信息
      const getDepartInfo = (val, names, record) => {
        console.log({ val, names });
        record.deptNames = names.join(',');
      };

      const getFlowInfo = (val, names, record) => {
        console.log({ val, names });
        // record.typeCode = names.join(',');
      };

      //第一个文件change
      const handleBeforeUploadFilename = (file, { key, record }) => {
        console.log('file, record', file, record);
        record[key] = file;
        return false;
      };
      async function handleEdit(record) {
        console.log('handleEdit', record);
        try {
          handleSetProps(true);
          const params = setParams(record);
          let Files = new FormData();
          for (let v in params) {
            Files.append(v, params[v]);
          }
          await getPaperUpdate(Files);
          createMessage.success('操作成功');
          handleSuccess();
        } finally {
          handleSetProps(false);
        }
      }

      async function handleDelete(record) {
        try {
          const params = {
            id: record.id,
          };
          handleSetProps(true);
          await getPaperDel(params);
          createMessage.success('操作成功');
          handleSuccess();
        } catch (err) {
          console.error(err);
        } finally {
          handleSetProps(false);
        }
      }

      function handleSuccess() {
        reload();
      }

      const handleDown = async (record, type) => {
        console.log({ record, type });
        let params = {
          id: record.id,
        };
        if (type == 2) {
          params['type'] = 'tail';
        }
        let title = type == 1 ? '文件头' : '文件尾' + '.xls';
        try {
          handleSetProps(true);
          const { headers, data } = await getFlowGetTemplateFile(params);
          console.log('res', { headers, data });
          if (headers['content-disposition']) {
            title = decodeURIComponent(headers['content-disposition'].split('=').pop());
          }
          console.log('title', title);
          if (data) {
            downloadByData(data, title);
          }
        } catch (err) {
          console.error('handleDown', err);
        } finally {
          handleSetProps(false);
        }
      };
      const handleSetProps = (bool: boolean) => {
        setProps({ loading: bool });
      };

      return {
        registerTable,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleCreate,
        departList,
        getDepartInfo,
        unitCodeList,
        handleBeforeUploadFilename,
        handleDown,
        handleSave,
        getFlowInfo,
        flowTree,
      };
    },
  });
</script>
